<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import useUpload from '@renderer/composables/useUpload'
import { ref, watch } from 'vue'
const { uploadAvatarImage } = useUpload()

const props = withDefaults(
  defineProps<{
    name?: string
    modelValue: string
  }>(),
  { name: 'file' },
)

const imageUrl = ref(props.modelValue)
watch(
  () => props.modelValue,
  (url) => {
    imageUrl.value = url
  },
)
const emit = defineEmits<{
  (e: 'update:modelValue', url: string): void
  (e: 'finish', url: string): void
}>()

//上传到服务器
const upload = async (file: any) => {
  const form = new FormData()
  form.append(props.name, file)
  const fileInfo = await uploadAvatarImage(form)
  imageUrl.value = fileInfo.src
  emit('update:modelValue', imageUrl.value!)
  emit('finish', imageUrl.value!)
}

const request = async (options: any) => {
  upload(options.file)
}
</script>

<template>
  <el-upload action="" class="avatar-uploader" :http-request="request" :show-file-list="false">
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<style scoped>
.avatar-uploader .avatar {
  height: 50px;
  width: 50px;
  display: block;
  @apply bg-gray-200;
}
</style>

<style>
.avatar-uploader .el-upload {
  @apply border;
  border-radius: 12px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}
</style>
